"""
用户账户相关功能：注册、短信、登录、注销
"""
from django.shortcuts import render, redirect, HttpResponse, reverse
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm
from django.http import JsonResponse
from web import models
import uuid, datetime


def register(request):
    """
    注册功能
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})

    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，写入数据库（密码要是密文）
        # 在自动剔除用户表中不存在的字段的前提下，在数据库中的用户信息表中新增一条数据并将新增的这条数据赋值给instance
        instance = form.save()  # instance即当前用户信息类实例化的对象

        # 注册成功的用户即给个人免费版的使用权限，即在交易信息记录中插入一条数据
        policy_object = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            count=0,
            price=0,
            start_datetime=datetime.datetime.now(),
            price_policy=policy_object,
            user=instance,
        )

        return JsonResponse({'status': True, 'data': '/login/'})

    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """
    发送短信功能
    :param request:
    :return:
    """
    form = SendSmsForm(request, data=request.GET)
    # 只是校验手机号：不能为空、格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """
    短信登录
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'login_sms.html', {'form': form})
    form = LoginSMSForm(request.POST)
    if form.is_valid():
        # 如果用户输入正确，登录成功
        mobile_phone = form.cleaned_data['mobile_phone']

        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        # 将当前用户的id保存为session信息
        request.session['user_id'] = user_object.id
        # 将session信息的超时时间改为两周！
        request.session.set_expiry(60 * 60 * 24 * 14)

        return JsonResponse({"status": True, 'data': "/index/"})

    return JsonResponse({"status": False, 'error': form.errors})


def img_code(request):
    """
    生成图片验证码
    :param request:
    :return:
    """
    from utils.img.imgcode import check_code
    from io import BytesIO

    img_obj, code = check_code()

    request.session['img_code'] = code
    request.session.set_expiry(60)  # 主动修改session的过期时间为60s

    stream = BytesIO()
    img_obj.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def login(request):
    """
    用户名密码登录
    :param request:
    :return:
    """
    form = LoginForm(request)
    if request.method == 'POST':
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            from django.db.models import Q
            # 判断用户输入的邮箱或手机号 与 密码是否正确
            user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
                password=password).first()
            if user_object:
                # 如果输入正确则将当前用户的id保存在session信息中
                request.session['user_id'] = user_object.id
                # 将session信息的超时时间改为两周
                request.session.set_expiry(60 * 60 * 24 * 14)

                return redirect('index')

            # 将错误信息添加到username字段中
            form.add_error('username', '用户名或密码错误')

    return render(request, 'login.html', {'form': form})


def logout(request):
    """
    注销
    :param request:
    :return:
    """
    request.session.flush()
    # 清除session信息
    return redirect('index')



